import React, {Component} from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableHighlight,
  Platform,
  PermissionsAndroid,
  TouchableOpacity,
  ScrollView,
  Image,
  Keyboard,
  ProgressViewIOS,
  Alert,
  Animated,
} from 'react-native';

import {
  Button,
} from 'react-native-elements';
// import Record from 'react-native-record-sound';
import dismissKeyboard from 'dismissKeyboard';

import Config from '../../config';
import BasePage from '../common/BasePage';
import TImageUpLoadMultiComponent from '../../components/TImageUpLoadMultiComponent';
import Constants from '../../common/Constants';
import ToastUtils from '../../common/ToastUtils';
import SizeUtils from '../../common/SizeUtils';
import Sound from 'react-native-sound';
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import DataManager from '../../datas/DataManager';

const RECORD_MIN_TIME = 30;
export default class ActivityEnterSingerPage extends BasePage {
  constructor(props) {
    super(props);

    this.state = {
      enter_state: 0,
      isRecording:false,
      recordFinish:false,
      soundCurrentTime:0,
      soundTotalTime:0,
      recordingTime:0,
    }
    this.audioConfig = {
      currentTime: 0.0,
      recording: false,
      stoppedRecording: false,
      finished: false,
      audioKey:"",
      audioPath: "",
      hasPermission: undefined,
      tick:null,
      isPlaying:false,
    };
    this.sound = null;

    this.enterData = {
        activityData:this.props.pageData.routeData,
        avatar_url:"",
        content:"",
        media_url:"",
    }
    this._isUploadedImage = false;
    this._goEdit = false;
    this._recordTick = null;
    this._imageComponent = null;
  }

 componentDidMount() {
    // 初始化配置
    this._checkPermission().then((hasPermission) => {
      this.audioConfig.hasPermission = hasPermission;
      if (!hasPermission) return;

      // 录音中
      AudioRecorder.onProgress = (data) => {
        // 设置录音的时候
        this.audioConfig.currentTime = data.currentTime;
      };

      // 苹果的stop在这处理，安卓的stop在stopRecord里处理
      AudioRecorder.onFinished = (data) => {
        console.log("结束录音")
        if (Platform.OS === 'ios') {
          this._finishRecording(data.status === "OK", data.audioFileURL);
        }
      };

      this.audioConfig.audioKey = Constants.RANDOM_UPLOAD_NAME(32) + ".m4a";
      this.audioConfig.audioPath = AudioUtils.DocumentDirectoryPath + "/" + this.audioConfig.audioKey;
      if (Platform.OS === 'ios') {
        AudioRecorder.prepareRecordingAtPath(this.audioConfig.audioPath,{AudioEncoding:"aac"});
      }
    });
  }

  componentWillUnmount() {
    this._clearTimer();
  }

  _dealLeavePage() {
    if(this._goEdit === true) {
      return;
    }
    this.setState({
      enter_state:0,
      isRecording:false,
      recordFinish:false,
      soundCurrentTime:0,
      soundTotalTime:0,
      recordingTime:0,
    })
    this._isUploadedImage = false;
    this.clearAudio();
    this._onPressRetry();
    this._clearRecordTick();
    this._imageComponent.reset();
  }

  _checkPermission() {
    if (Platform.OS !== 'android') {
      return Promise.resolve(true);
    }

    const rationale = {
      'title': 'Microphone Permission',
      'message': 'AudioExample needs access to your microphone so you can record audio.'
    };

    return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, rationale)
      .then((result) => {
        console.log('Permission result:', result);
        return (result === true || result === PermissionsAndroid.RESULTS.GRANTED);
      });
  }

  render() {
    return(
      <View style={{flex:1, backgroundColor:"#db3132"}}>
        <ScrollView keyboardShouldPersistTaps={"never"}
            ref={(ref) => {this._scrollView = ref}} style={{backgroundColor:"#ffffff", paddingTop:Config.paddingTop}}>
          <View style={{flexDirection:"column", alignItems:"center"}}>
            {this._renderImage()}
            {this._renderUploadSound()}
          </View>
        </ScrollView>
        {this._renderNavigationBar()}
        {this._renderNextBtn()}
      </View>
    )
  }

  _renderImage() {
    return(
      <View style={{flexDirection:"row", justifyContent:"center",
          paddingTop:SizeUtils.translateDesignHeightToCode(30),
        }}>
        <TImageUpLoadMultiComponent style={{
            width:SizeUtils.translateDesignWidthToCode(212), height:SizeUtils.translateDesignWidthToCode(212)}}
            imageStyle={{width:212, height:212}}
          ref={(ref) => this._imageComponent = ref}/>
      </View>
    )
  }

  //上传声音
  _renderUploadSound() {
    return(
      <View style={{flexDirection:"column", alignItems:"center", backgroundColor:"#ffffff"}}>
        <Text style={{paddingTop:SizeUtils.translateDesignHeightToCode(32),
            fontSize:SizeUtils.translateFontSizeToCode(34), color:"#222222", textAlign:"center"}}>
            上传你的头像</Text>
        {this._renderRecord()}
        {this._renderRecordButton()}
      </View>
    )
  }

  _renderRecord() {
    if(this.state.recordFinish) {
      return(
        <View style={{flexDirection:"row", borderRadius:SizeUtils.translateDesignNumToCode(10), borderWidth:SizeUtils.translateDesignNumToCode(3),
          borderColor:"#eeeeee", width:SizeUtils.translateDesignWidthToCode(669), height:SizeUtils.translateDesignHeightToCode(76),
          alignItems:"center", marginTop:SizeUtils.translateDesignHeightToCode(30)}}>
          <TouchableOpacity onPress={this._onPressPlay.bind(this)} style={{height:SizeUtils.translateDesignHeightToCode(76),
              flexDirection:"row", alignItems:"center"}}>
            <Image source={require("../../../resource/images/activity/play.png")} style={{width:SizeUtils.translateDesignWidthToCode(26),
              height:SizeUtils.translateDesignWidthToCode(26), marginLeft:SizeUtils.translateDesignWidthToCode(10)}}/>
          </TouchableOpacity>
          <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(24), marginLeft:SizeUtils.translateDesignWidthToCode(12)}}>
            {this._getCurrentTimeText()}
          </Text>
          <View style={{width:SizeUtils.translateDesignWidthToCode(410), marginLeft:SizeUtils.translateDesignWidthToCode(12),
            backgroundColor:"#cccccc00", height:SizeUtils.translateDesignHeightToCode(20)}}>
            {this._renderProgressBar()}
          </View>
          <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(24), marginLeft:SizeUtils.translateDesignWidthToCode(7)}}>
            {this._getTotalTimeText()}
          </Text>
          <TouchableOpacity onPress={this._onPressRetry.bind(this)} style={{height:SizeUtils.translateDesignHeightToCode(76),
              flexDirection:"row", alignItems:"center"}}>
            <Image source={require("../../../resource/images/activity/again.png")} style={{width:SizeUtils.translateDesignWidthToCode(19),
              height:SizeUtils.translateDesignWidthToCode(18), marginLeft:SizeUtils.translateDesignWidthToCode(12)}}/>
          </TouchableOpacity>
        </View>
      )
    }
  }

  _renderRecordButton() {
    return (
      <Button
          buttonStyle={{width:SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80),
             height:SizeUtils.translateDesignHeightToCode(75),
              marginTop:SizeUtils.translateDesignHeightToCode(32)}}
          title={this._getUploadBtnText()}
          backgroundColor={this._getUpdateBtnColor()}
          borderRadius={SizeUtils.translateDesignNumToCode(12)}
          onPress={() => {
              this._onPressRecoredButton();
            }
          }
      />
    )
  }

  _onPressRecoredButton() {
    if(this.audioConfig.finished === true) {
      if(this.audioConfig.isPlaying === true) {
        this._stopPlay();
      }
      else {
        this._play();
      }
    }
    else if(this.audioConfig.recording === false) {
      this._record();
    }
    else {
      this._recordStop();
    }
  }

  _getUpdateBtnColor() {
    return "#db3132";
  }

  _renderProgressBar() {
    if(Platform.OS === "ios") {
      return(
        <ProgressViewIOS style={{height:SizeUtils.translateDesignHeightToCode(20)}}
          progressTintColor="#db3132" progress={this._getProgress()}/>
      )
    }
  }

  _getProgress() {
    return this.state.soundCurrentTime / this.state.soundTotalTime;
  }

  _getCurrentTimeText() {
    //soundCurrentTime  单位秒
    return this._getTimeText(this.state.soundCurrentTime)
  }

  _getTotalTimeText() {
    //soundTotalTime  单位秒
    return this._getTimeText(this.state.soundTotalTime)
  }

  _getTimeText(time) {
    time = Math.ceil(time);
    if(time == 0) {
      return "00:00";
    }
    let minutes = Math.floor(time / 60);
    let second = time - minutes * 60;
    let minutesStr = minutes < 10 ? ("0" + minutes) : minutes;
    let secondStr = second < 10 ? ("0" + second) : second;
    return minutesStr + ":" + secondStr;
  }

  //点击播放声音
  _onPressPlay() {
    this._play();
  }

  //点击重新录音
  _onPressRetry() {
    this._stopPlay();
    this.clearAudio();
    this.setState({
      recordFinish:false,
      soundCurrentTime:0
    })
  }

  _getUploadBtnText() {
    let text = "点击按钮开始录音";
    if(this.state.recordFinish === true) {
      if(this.audioConfig.isPlaying) {
        text = "停止播放录音";
      }
      else {
        text = "点击播放录音";
      }
    }
    else if(this.state.isRecording === true) {
      text = "点击停止录制,当前:" + this.state.recordingTime + "秒";
    }
    return text;
  }

  _renderNextBtn() {
    return (
      <View style={{position: "absolute", bottom:0}}>
        <Button
            buttonStyle={{width:SizeUtils.getWindowSize().width, height:SizeUtils.translateDesignHeightToCode(90),
              backgroundColor:"#db3132", marginLeft:0, marginRight:0}}
            textStyle={{color:"#ffffff", fontSize:SizeUtils.translateFontSizeToCode(32), textAlign:"center"}}
            disabled={this._getBtnDisable()}
            title={this._getEnterBtnTitle()}
            onPress={() => {
                this._goNext();
              }
            }
        />
      </View>
    )
  }

  _getBtnDisable() {
    return this.state.enter_state != 0;
  }

  _goNext() {
    if(this.sound == null){
      ToastUtils.show("请录入声音");
      return;
    }
    let currentImageDatas = this._imageComponent.getCurrentImageDatas();
    if(currentImageDatas == null || currentImageDatas.length == 0){
      ToastUtils.show("请上传头像");
      return;
    }

    this._uploadSound();
    ToastUtils.show("正在上传数据，请稍后...");
    this.setState({
      enter_state:1,
    })
  }

  _onUploadCallback(imageUrls) {
    console.log("上传图片完成..." + imageUrls);
    if(this._leave === true) {
      return;
    }
    this._isUploadedImage = true;
    if(imageUrls && imageUrls.length > 0) {
      this.enterData.avatar_url = imageUrls[0];
    }
    else {
      this.enterData.avatar_url = "";
    }
    this.gotoPage(Config.pages.activity_entrySinger_text, {enterData:this.enterData, length:[10, 500]});
  }

  _getEnterBtnTitle() {
    if(this.state.enter_state === 1) {
      return "正在上传数据...";
    }
    return "下一步";
  }

  _uploadSound(){
    console.log("开始上传声音...");
    DataManager.modelDic[Constants.MODULE_TYPE.ALI_OSS].uploadFile(this.audioConfig.audioKey,this.audioConfig.audioPath,function(pre,res){
      if(this._leave === true) {
        return;
      }
      this.enterData.media_url = Config.aliUrl +pre+this.audioConfig.audioKey;
      console.log("上传声音完成..." + this.enterData.media_url);
      console.log("开始上传图片...");
      this._imageComponent.doUpload(this._onUploadCallback.bind(this));
    },this);
  }

 _record() {
    if (Platform.OS === 'android') {
      AudioRecorder.prepareRecordingAtPath(this.audioConfig.audioPath,{AudioEncoding:"aac"});
    }
    if (this.audioConfig.recording) {
      console.warn('Already recording!');
      return;
    }

    if (!this.audioConfig.hasPermission) {
      console.warn('Can\'t record, no permission granted!');
      return;
    }

    console.log("开始录音")
    let self = this;
    try {
      AudioRecorder.startRecording();
      this.setState({
        isRecording:true,
        recordingTime:0,
      });
      this.audioConfig.recording = true;
      this._recordTick = setInterval(function(){
        self.setState({
          recordingTime:self.state.recordingTime + 1,
        })
      },1000);
    } catch (error) {
      console.error(error);
    }
  }

  _clearRecordTick() {
    if(this._recordTick != null) {
      clearInterval(this._recordTick);
      this._recordTick = null;
    }
  }

  // _startRecordTimer() {
  //   setInterval(function(){
  //     this.setState({
  //
  //     })
  //   },1000);
  // }

//停止录音
 async _recordStop() {
      if (!this.audioConfig.recording) {
        console.warn('Can\'t stop, not recording!');
        return;
      }
      this._clearRecordTick();
      this.audioConfig.stoppedRecording=true;
      this.audioConfig.recording = false;
      this.setState({
        isRecording:false,
      })
      try {
        const filePath = await AudioRecorder.stopRecording();

        if (Platform.OS === 'android') {
          this._finishRecording(true, filePath);
        }
        return filePath;
      } catch (error) {
        console.error(error);
      }
  }

  // 录音完成
   _finishRecording(didSucceed,filePath) {
    console.log("完成录音")
    this.audioConfig.finished = didSucceed;
    setTimeout(() => {
      this.sound = new Sound(this.audioConfig.audioPath, '', (error) => {
        if (error) {
          console.log('failed to load the sound', error);
          return;
        }
        if(this.sound._duration < RECORD_MIN_TIME || this.sound._duration > 60 * 5) {
          ToastUtils.show("录音时间请控制在" + RECORD_MIN_TIME + "秒-300秒");
          this.sound = null;
          this.audioConfig.finished = false;
        }
        else {
          this.setState({
            recordFinish:true,
            soundTotalTime: this.sound._duration,
          })
        }
      });
      //这里加载完才算完成
    }, 10);
  }

  // 清除当前的录音数据
  clearAudio(){
    this.audioConfig.currentTime = 0.0;
    this.audioConfig.recording = false;
    this.audioConfig.stoppedRecording = false;
    this.audioConfig.finished = false;
    this.sound = null;
  }

   _play(){
    if(this.sound == null){
      console.log("sound not find");
      return;
    }
    if(this.audioConfig.tick != null){
      console.log("还没播放完又开始了？");
      return;
    }
    this.setState({
      soundCurrentTime:0,
      isPlaying:true,
    })
    var myself = this;

    this.sound.play((success) => {
      this._stopPlay();
      if (success) {
        console.log('successfully finished playing');
      } else {
        console.log('playback failed due to audio decoding errors');
      }
    });
    this.audioConfig.isPlaying = true;
    this.audioConfig.tick = setInterval(function(){
      myself.sound.getCurrentTime(function(ctime, isPlaying){
        if(!isPlaying){
          // 播放完了
          myself._stopPlay();
        }
        else {
          myself.setState({
            soundCurrentTime: ctime,
          })
        }
      });
    },100);
  }

  _clearTimer() {
    if(this.audioConfig.tick != null){
      clearInterval(this.audioConfig.tick);
      this.audioConfig.tick = null;
    }
  }

  _stopPlay() {
    if(this.sound == null){
      console.log("sound not find by stop");
      return;
    }
    this.audioConfig.isPlaying = false;
    this.setState({
      isPlaying:false,
      soundCurrentTime: this.state.soundTotalTime,
    });
    this._clearTimer();
    this.sound.stop();
  };
}
